package indi.readbook.example.admin.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import indi.readbook.example.admin.service.UserService;
import indi.readbook.example.common.entity.system.UserDO;
import indi.readbook.example.common.exception.NotLoginException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhangguowei
 */
@Controller
public class BaseController {

	@Autowired
	UserService userService;

	public UserDO getUser() {
		if (RequestContextHolder.getRequestAttributes() != null){
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			String token = request.getHeader("token");

			// 执行认证
			if (token == null) {
				throw new NotLoginException("无token，请重新登录");
			}
			// 获取 token 中的 user id
			String userIdStr;
			try {
				userIdStr = JWT.decode(token).getAudience().get(0);
			} catch (JWTDecodeException j) {
				throw new NotLoginException("401");
			}
			UserDO user = userService.get(Long.valueOf(userIdStr));
			if (user == null) {
				throw new NotLoginException("用户不存在，请重新登录");
			}
			return user;
		}else{
			throw new NotLoginException("获取用户登录凭证失败");
		}
	}

	public Long getUserId() {
		return getUser().getUserId();
	}

	public String getUsername() {
		return getUser().getUsername();
	}
}